package main

import (
	"bufio"
	"encoding/base64"
	"fmt"
	"log"

	"golang.org/x/crypto/ssh"
)

// SSHConfig 包含 SSH 连接所需的信息
type SSHConfig struct {
	Host       string
	Port       int
	User       string
	PrivateKey string
}

func main() {
	sshconfig := &SSHConfig{
		Host: "172.31.6.111",
		Port: 22,
		User: "root",
		//cat /root/.ssh/id_rsa |base64 -w 0
		PrivateKey: "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUJsd0FBQUFkemMyZ3RjbgpOaEFBQUFBd0VBQVFBQUFZRUFsV1M1WnJ1N0dIaEFESDByNGlpb3l6Q3NQSmViMkIxQ0xxOUFGd3FVT1dLWTNXYTVqQUhFClZqNG1WY3ZnL1UzRHFhSVl3RklGWjlLUDh2SEs1NmtJU0gzTnM2MUozWHlvNS84bGYwSTNBUlRSNHRYOXE3aEFGM3JUMFIKUmNPU3ZVYW9aNzZhQlpseGFTUUtsRTE3Z0hPczRER2w1cjgySVpXei9kSndXQ1B3NzB2eXlwdmZGb2FnQ2dGT252Z0VuLwpOS0hKVmJITHp3U1NKWnNVUDNKMVBwajFuUnVVRUZubUJweExMdk9hVS9BZ0V6REpDN3hpbncyZFczMHluN1VjbnNVK3NyCkw3WFU0Vm4xUnhRNHJ5cndwaVlYMFNHa3UxV2Z3a1lqQTkzRlJtNGRFOGErallBdit4VUhZcS83S0hOajNQV0hFU1FLeHIKWGhJdzZOY0luMUE4OGRvVFJJWnhma3pydDNUb2txeGtLYnpGaFpHcjZ6OXhMOFo2UzNJSTR3a2s1WUx6dUxMSVNieSs2ZQpEMXo2YTFzRVlVam5VWWVJN2VvOFV2SW1sZHZ4S3pNdlVPVHBwMGxtRk51Z3MwRzNzdHZ2VWtWbjkyNEl6YTdrK0lIa3FYCjVFSVBXTUNXa3dHSlpXRjNGc2RHY0F1czF6Zmw0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DdEhKMDM1Ui85ampodjVBcU5JQwpQV0VHNG92SFJuZmlRa2VKa0kwaHJ4b1E2NG9QNTA5UUFBQU1FQXpSOTgyZnYxMGhjVitzN2puUnB2anNkcG91b0RpSXlECnN3RWpzQU5MM3RLUFF0TUM1dks1c1dPNFJ6aTVWQWc1bytZZnZHbzNrTGhFSXhZcGU1NmRNUFpzV0x0bGZqcXdYYld2N2cKWEppdFRZQ21YR1oyWktxTGFpK28yaHM1aGFsSTlLL2JUZlJQc2EwQWU2ait6WlBzazUxWm9uYm5RemFldW1HcEEwOEVqQQpobWVGdVFSRi9iRjduTGo1Z3lqVFhJVlRjWGlubmpURkZQYWFwREVpUTdqRmkyVzIrcjZsd3paSE5idVVPZFZpdURBV1oyCmozbFd3ZWJJMzBrKy9WQUFBQUMzSnZiM1JBYldGemRHVnlBUUlEQkFVR0J3PT0KLS0tLS1FTkQgT1BFTlNTSCBQUklWQVRFIEtFWS0tLS0tCg==",
	}

	result, err := remote_cmd(sshconfig, "df -h")
	if err != nil {
		log.Fatalf("执行命令失败: %v", err)
	}
	fmt.Println(result)
}

func remote_cmd(sshconfig *SSHConfig, cmd string) (string, error) {
	var auth []ssh.AuthMethod
	var result string
	// 解析私钥
	decodekey, err := base64.StdEncoding.DecodeString(sshconfig.PrivateKey)
	if err != nil {
		return "", err
	}
	key, err := ssh.ParsePrivateKey(decodekey)
	if err != nil {
		return "", err
	}
	auth = append(auth, ssh.PublicKeys(key))
	config := &ssh.ClientConfig{
		User:            sshconfig.User,
		Auth:            auth,
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}

	client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", sshconfig.Host, sshconfig.Port), config)
	if err != nil {
		return "", err
	}
	defer client.Close()

	session, err := client.NewSession()
	if err != nil {
		return "", err
	}
	defer session.Close()

	stdout, err := session.StdoutPipe()
	if err != nil {
		return "", err
	}

	if err := session.Run(cmd); err != nil {
		return "", err
	}

	scanner := bufio.NewScanner(stdout)
	for scanner.Scan() {
		result += scanner.Text() + "\n"
	}

	return result, nil
}
